<template>
  <div>
    <el-dialog :title="`${formData.phaseDesc}`" :visible.sync="isShowADM" :close-on-click-modal="false"
      :before-close="handleClose" :width="screenWidth > 1310 ? '55%' : '70%'" v-dialogDrag>
      <el-form :model="formData" label-width="85px" ref="ruleForm" :rules="formRules" size="small" :hide-required-asterisk="true">
        <el-row :gutter="24" class="gz-form-row">
          <el-col :xs="5" :sm="4" :md="4" :lg="3" :xl="3">
            <el-form-item label="" label-width="0">
              <el-checkbox v-model="formData.isAuto">{{$t('common.auto_start')}}</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="10" :md="8" :lg="8" :xl="6">
            <el-form-item :label="$t('common.start_delay')" label-width="80px" class="inputPadding">
              <el-input type="number" v-model="formData.delayTime">
                <template slot="append">min</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="4" :md="4" :lg="3" :xl="3">
            <el-form-item label="" label-width="0">
              <el-checkbox v-model="formData.mode">{{$t('common.operation_signature')}}</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="5" :md="5" :lg="3" :xl="3">
            <el-form-item label="" label-width="0">
              <el-checkbox v-model="formData.checks">{{$t('common.review_confirmation')}}</el-checkbox>
            </el-form-item>
          </el-col>

          <el-col :xs="9" :sm="9" :md="8" :lg="6" :xl="6">
            <el-form-item :label="$t('basic.stage_name')">
              <el-input disabled v-model="formData.phaseDesc" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="9" :sm="9" :md="8" :lg="6" :xl="6">
            <el-form-item :label="$t('basic.reason_group')">
              <el-select v-model="formData.reasGrpId" remote filterable :remote-method="remoteMethodCause" placeholder="" clearable
                @clear="clearCause">
                <el-option v-for="(item,index) in causeList" :key="index" :label="item.reasGrpDesc" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
            <el-form-item label-width="0" class="btnGourd">
              <el-button type="primary" size="mini" :disabled="isreadOnly" @click="handleAdd()">{{ $t("common.add") }}</el-button>
              <el-button type="primary" size="mini" :disabled="isreadOnly" @click="handleEdit()">{{ $t("common.edit") }}</el-button>
              <el-button type="primary" size="mini" :disabled="isreadOnly" @click="handleDel()">{{ $t("common.remove") }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div>
        <el-row :gutter="24">
          <el-col :xs="24">
            <div class="tableAuto">
              <el-table :data="tableData" height="180px" @row-click="rowClick" style="width:100%" border stripe v-loading="tableLoading"
                :header-cell-style="{background:'#EAEBEC'}" ref="refTable" highlight-current-row>
                <el-table-column label="" width="50" align="center">
                  <template slot-scope="scope">
                    <div>
                      <el-radio :label="scope.row.fid" v-model="radioId">&nbsp;</el-radio>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column type="index" :label="$t('common.number')" width="50" align="center"></el-table-column>
                <el-table-column prop="itemId" show-overflow-tooltip :label="$t('basic.material')"></el-table-column>
                <el-table-column prop="qty" show-overflow-tooltip :label="$t('common.feed_quantity')"></el-table-column>
                <el-table-column prop="hi" show-overflow-tooltip :label="$t('common.upper_limit')"></el-table-column>
                <el-table-column prop="lo" show-overflow-tooltip :label="$t('common.lower_limit')"></el-table-column>
                <el-table-column prop="uom" show-overflow-tooltip :label="$t('basic.company')"></el-table-column>
                <el-table-column :label="$t('common.to_sort')" show-overflow-tooltip prop="desc" width="100">
                  <template slot-scope="scope">
                    <img src="../../../../static/image/shang.png" alt="" :class="isreadOnly ? 'allowed' : ''"
                      style="height:25px;margin-right:10px;cursor: pointer;" @click.stop="moveUp(scope.$index,scope.row)">
                    <img src="../../../../static/image/xia.png" alt="" :class="isreadOnly ? 'allowed' : ''"
                      style="height:25px;cursor: pointer;" @click.stop="moveDown(scope.$index,scope.row)">
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
          <el-col :xs="24">
            <div class="pagination-area">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 20, 50, 100]"
                :page-size="pagerTab.pageSize" :current-page="pagerTab.pageNum" layout="total, sizes, prev, pager, next, jumper"
                :total="pagerTab.total">
              </el-pagination>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-form :model="formData" label-width="85px" ref="ruleForm" size="small" :hide-required-asterisk="true">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label-width="0">
              <p style="font-weight: bold">{{$t('recipe.phase_info')}}</p>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item :label="$t('recipe.info_confirm')">
              <el-input rows="3" type="textarea" v-model="formData.guideInfo" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item :label="$t('basic.remarks')">
              <el-input rows="3" type="textarea" v-model="formData.flastModifyComment" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" :disabled="isreadOnly" :loading="loading" @click="handleConfirmStorage('ruleForm')">保
          存</el-button>
        <el-button @click="handleClose()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>

    </el-dialog>

    <el-dialog :title="title" v-dialogDrag :visible.sync="isAddDialog" :close-on-click-modal="false" :before-close="handleCloseAdd"
      :width="screenWidth > 1024 ? '30%' : '55%'">
      <el-form :model="ruleForm" label-width="85px" ref="formName" size="small" :rules="rules" :hide-required-asterisk="true">
        <el-row :gutter="35">
          <el-col :xs="24">
            <el-form-item :label="$t('basic.material')" prop="itemId" class="material">
              <el-select v-model="ruleForm.itemId" remote filterable :remote-method="remoteMethodMaterial" placeholder=""
                v-el-select-loadmore="loadMoreMaterialFun" clearable @clear="clearMaterial" @change="changeItemId">
                <el-option v-for="(item,index) in materialList" :key="index" :label="item.fid" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('recipe.the_number')" prop="qty">
              <el-input type="number" v-enterNumber2 v-model="ruleForm.qty" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('basic.company')" prop="uom">
              <el-input type="text" disabled v-model="ruleForm.uom" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('common.upper_limit')" prop="hi">
              <el-input type="number" v-enterNumber2 v-model="ruleForm.hi" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('common.lower_limit')" prop="lo">
              <el-input type="number" v-enterNumber2 v-model="ruleForm.lo" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" :disabled="isreadOnly" :loading="loadingTab" @click="handleConfirm('formName')">保
          存</el-button>
        <el-button @click="handleCloseAdd()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { configure } from "@/api/configure"
import { formula } from "@/api/formula"
export default {
  props: {
    isShowADM: Boolean,
    tdIndex: Number,
    stepObj: Object,
    isreadOnly: Boolean
  },
  data () {
    let HiFn = (rule, value, callback) => {
      if (value) {
        if (parseFloat(this.ruleForm.qty) > parseInt(value)) {
          callback(new Error('物料上限不能小于物料数量'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    let LoFn = (rule, value, callback) => {
      if (value) {
        if (parseFloat(value) > parseFloat(this.ruleForm.qty)) {
          callback(new Error('物料下限不能大于物料数量'));
        } else if (this.ruleForm.hi) {
          if (parseFloat(value) > parseFloat(this.ruleForm.hi)) {
            callback(new Error('物料下限不能大于物料上限'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    return {
      screenWidth: document.body.clientWidth,
      formData: {
        seqNo: "",
        delayTime: "",
        mode: "",
        checks: "",
        stepNo: "",
        stepDesc: "",
        isActive: false,
        isAuto: false,
        signitature: "",
        phaseDesc: "手动加料",
        reasGrpId: "",
        flastModifyComment: "",
        guideInfo: "",
        stepSort: 0,
      },
      tableData: [],
      radioId: "",
      title: "添加",
      isAddDialog: false,
      ruleForm: {
        itemId: "",
        qty: "",
        uom: "",
        hi: "",
        lo: "",
        seq: "",
      },
      materialList: [],
      loading: false,
      rules: {
        itemId: [{ required: true, message: '物料名称不能为空', trigger: 'change' }],
        qty: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
        hi: [{ validator: HiFn, trigger: 'blur' }],
        lo: [{ validator: LoFn, trigger: 'blur' }]
      },
      formRules: {
        // stepDesc:[{ required: true, message: '步序名称不能为空', trigger: 'change' }],
      },
      pager: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      keyword: "",
      stepLoading: false,
      tableLoading: false,
      loadingTab: false,
      pagerTab: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      pagerGroup: {
        pageNum: 1,
        pageSize: 50,
        keyword: ""
      },
      causeList: [],
      isSort: false
    }
  },
  watch: {
    screenWidth (val) {
      this.screenWidth = Number(val)
    },
    isShowADM (val) {
      if (val) {
        this.radioId = ''
        this.formData.stepDesc = this.stepObj.stepDesc ?? this.stepObj.texts
        this.formData.isActive = this.stepObj.isActive == 1 ? true : false
        this.formData.seqNo = this.tdIndex
        this.formData.stepNo = this.tdIndex
        this.formData.mode = this.stepObj.mode == 1 ? true : false
        this.formData.isAuto = this.stepObj.isAuto == 1 ? true : false
        this.formData.checks = this.stepObj.checks == 1 ? true : false
        this.formData.delayTime = this.stepObj.delayTime ?? 0
        this.formData.fid = this.stepObj.fid
        this.formData.phaseDesc = this.stepObj.texts
        this.formData.reasGrpId = this.stepObj.reasGrpId
        this.formData.flastModifyComment = this.stepObj.flastModifyComment
        this.formData.guideInfo = this.stepObj.guideInfo
        this.formData.stepSort = this.stepObj.stepSort ?? 0
        if (this.stepObj.fid) {
          this.phaseAdmList()
        } else {
          this.tableData = []
          this.pager.total = 0
        }
      }
    }
  },
  mounted () {
    const that = this
    window.addEventListener('resize', function () {
      that.screenWidth = document.body.offsetWidth;
    })
  },
  created () {
    this.getReasGroupList()
    this.getItemList()
  },
  methods: {
    getItemList () {
      const param = {
        className: this.keyword,
        page: this.pager.pageNum,
        size: this.pager.pageSize,
        itemClassVo: {
          consumed: 1
        }
      }
      configure.getItemList(param).then(res => {
        if (res.code == 200) {
          this.materialList = [...this.materialList, ...res.data.rows]
        }
      })
    },
    handleClose () {
      this.$emit("closePH", "ADM")
    },
    handleConfirmStorage (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const param = {
            phaseDesc: this.formData.phaseDesc,
            isAuto: this.formData.isAuto == false ? 0 : 1,
            isActive: this.formData.isActive == false ? 0 : 1,
            checks: this.formData.checks == false ? 0 : 1,
            delayTime: this.formData.delayTime,
            operationId: this.stepObj.operationId,
            type: this.stepObj.type,
            mode: this.formData.mode == false ? 0 : 1,
            seqNo: this.stepObj.seqNo,
            phaseCode: this.stepObj.phaseCode,
            stepNo: this.stepObj.stepNo,
            serialNo: this.stepObj.serialNo,
            reasGrpId: this.formData.reasGrpId,
            flastModifyComment: this.formData.flastModifyComment,
            guideInfo: this.formData.guideInfo,
            stepSort: this.formData.stepSort,
          }
          if (this.formData.fid) {
            param.fid = this.formData.fid
          }
          this.loading = true
          formula.phaseAdd(param).then(res => {
            this.loading = false
            if (res.code == 200) {
              let obj = {
                mode: this.stepObj.mode,
                isAuto: this.formData.isAuto == false ? 0 : 1,
                isActive: this.formData.isActive == false ? 0 : 1,
                operationId: this.stepObj.operationId,
                seqNo: this.stepObj.seqNo,
                serialNo: this.stepObj.serialNo,
                text: this.stepObj.phaseDesc
              }
              this.$emit("uptionData", obj)
              this.$emit("closePH", "ADM")
            } else {
              this.$message.error(res.msg);
            }
          })
        } else {
          return false
        }
      })
    },
    rowClick (row) {
      this.radioId = row.fid;
      this.$refs.refTable.setCurrentRow(row)
    },
    phaseAdmList () {
      const param = {
        phaseId: this.stepObj.fid,
        page: this.pagerTab.pageNum,
        size: this.pagerTab.pageSize
      }
      this.tableLoading = true
      formula.phaseAdmList(param).then(res => {
        this.tableLoading = false
        if (res.code == 200) {
          this.tableData = res.data.rows
          this.pagerTab.total = res.data.total
        }
      })
    },
    handleAdd () {
      this.ruleForm = {}
      try {
        this.$refs['formName'].resetFields();
      } catch (e) { }
      this.title = "添加"
      this.isAddDialog = true
    },
    handleEdit () {
      if (this.radioId === '') {
        this.$message.error('请选择修改数据');
        return
      }
      this.title = "编辑"
      formula.findPhaseAdm(this.radioId).then(res => {
        if (res.code == 200) {
          this.ruleForm = Object.assign({}, res.data)
          this.isAddDialog = true
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    async handleDel () {
      if (this.radioId === '') {
        this.$message.error('请选择要删除的数据');
        return
      }
      formula.findPhaseAdm(this.radioId).then(res => {
        if (res.code == 200) {
          let fid = res.data.fid
          let that = this
          this.$customConfirm({
            onok () {
              formula.phaseAdmRemove(fid).then(res => {
                if (res.code == 200) {
                  that.phaseAdmList()
                  that.radioId = ''
                  that.$message({ duration: 1000, type: 'success', message: '删除成功!' });
                }
              })
            }
          });
        }
      })
    },
    handleCloseAdd () {
      this.isAddDialog = false
    },
    remoteMethodMaterial (keyword) {
      this.keyword = keyword.trim();
      this.pager.pageNum = 1
      setTimeout(() => {
        this.materialList = []
        this.getItemList()
      }, 200)
    },
    loadMoreMaterialFun () {
      this.pager.pageNum++
      this.getItemList()
    },
    clearMaterial () {
      this.keyword = ""
      this.pager.pageNum = 1
      this.materialList = []
      this.getItemList()
    },
    handleConfirm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = {}
          if (this.title == '添加') {
            param = {
              itemId: this.ruleForm.itemId,
              uom: this.ruleForm.uom,
              qty: this.ruleForm.qty,
              phaseId: this.stepObj.fid,
              fid: this.stepObj.stepId,
              seq: this.pagerTab.total + 1,
              lo: this.ruleForm.lo,
              hi: this.ruleForm.hi,
            }
          } else {
            param = Object.assign({}, this.ruleForm)
          }
          this.loadingTab = true
          formula.phaseAdmAdd(param, this.title).then(res => {
            this.loadingTab = false
            if (res.code == 200) {
              this.isAddDialog = false
              this.phaseAdmList()
            } else {
              this.$message.error(res.msg);
            }
          })
        } else {
          return false
        }
      })
    },
    changeItemId (val) {
      this.ruleForm.uom = this.materialList.find(item => item.fid == val).uomId
    },
    handleSizeChange (val) {
      this.pagerTab.pageSize = val
      this.phaseAdmList()
    },
    handleCurrentChange (val) {
      this.pagerTab.pageNum = val;
      this.phaseAdmList()
    },
    remoteMethodCause (keyword) {
      this.pagerGroup.keyword = keyword.trim();
      this.pagerGroup.pageNum = 1
      setTimeout(() => {
        this.causeList = []
        this.getReasGroupList()
      }, 200)
    },
    clearCause () {
      this.pagerGroup.keyword = ""
      this.pagerGroup.pageNum = 1
      this.causeList = []
      this.getReasGroupList()
    },
    getReasGroupList () {
      const param = {
        reasGrpDesc: this.pagerGroup.keyword,
        page: this.pagerGroup.pageNum,
        size: this.pagerGroup.pageSize,
      }
      configure.getReasGroupList(param).then(res => {
        if (res.code == 200) {
          this.causeList = res.data.rows
        }
      })
    },
    moveUp (index, row) {
      if (this.isreadOnly) {
        return
      }
      if (index > 0) {
        if (this.isSort) {
          return
        }
        let upDate = this.tableData[index - 1];
        upDate.execSequence = index;
        this.tableData.splice(index - 1, 1);
        this.tableData[index - 1].execSequence = index - 1;
        this.tableData.splice(index, 0, upDate);
        const list = []
        this.tableData.forEach((item, index) => {
          list.push({
            fid: item.fid,
            sort: index
          })
        })
        this.isSort = true
        formula.batchModifySortAdm(list).then(res => {
          this.isSort = false
        }).catch(e => {
          this.isSort = false
        })
        this.$forceUpdate()
      } else {
        this.$message.warning("已经是第一条，不可上移");
      }
    },
    moveDown (index, row) {
      if (this.isreadOnly) {
        return
      }
      if (this.isSort) {
        return
      }
      if (index + 1 === this.tableData.length) {
        this.$message.warning("已经是最后一条，不可下移");
      } else {
        let downDate = this.tableData[index + 1];
        downDate.execSequence = index;
        this.tableData.splice(index + 1, 1);
        this.tableData.splice(index, 0, downDate);
        this.tableData[index + 1].execSequence = index + 1;
        const list = []
        this.tableData.forEach((item, index) => {
          list.push({
            fid: item.fid,
            sort: index
          })
        })
        this.isSort = true
        formula.batchModifySortAdm(list).then(res => {
          this.isSort = false
        }).catch(e => {
          this.isSort = false
        })
        this.$forceUpdate()
      }
    },
  },
}
</script>

<style scoped>
.rightAdd {
  color: #00a09d;
  cursor: pointer;
  font-size: 20px;
}
@media screen and (max-width: 1024px) {
  .tableAuto {
    width: 100%;
    overflow: auto;
  }
}
@media screen and (max-width: 1200px) {
  .btngroup {
    margin-bottom: 20px;
  }
}
.material >>> .el-select {
  width: 100%;
}
.pagination-area {
  padding: 10px;
}
</style>
